<?php

namespace G\User;

use Core\Support\Arr;
use Core\Support\SingleTon;
use Error;
use G\Rbac\Gate;
use G\User\Model\UserModel;

class UserService
{
    use SingleTon;

    protected $uid;

    /**
     * 创建用户
     */
    public function add()
    {
        # code...
    }

    public function list()
    {
        $paginate = UserModel::paginate();

        return [
            'count' => $paginate->count(),
            'data' => $paginate->items(),
            'perPage' => $paginate->perPage(),
            'total' => $paginate->total(),
        ];
    }

    /**
     * 更新用户信息
     */
    public function update(int $userId, array $data)
    {
        $user = UserModel::find($userId);

        // 权限鉴定
        if (!$user || Gate::not('user-update', ['creator' => $user->id])) {
            throw new Error("没有权限");
        }

        $user->update(Arr::only($data, [
            'name',
            'avatar',
            'gender',
            'phone',
            'mail',
        ]));
        return $user;
    }

    /**
     * 设置密码
     */
    public function setPassword($uid, $password)
    {
        $user = UserModel::find($uid);

        // 检查权限(管理员或者自己可以修改)

        // 设置密码
        if ($user) {
            $user->setPassword($password);
            $user->save();
        }
    }
}
